/*
 * 基于 Vue3 + Pixi.js 实现的互动数字信息墙 Demo
 * 功能：全屏大屏展示 + 可缩放 + 多点触控交互
*/

<template>
  <div ref="container" class="canvas-container"></div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue'
import * as PIXI from 'pixi.js'
import Hammer from 'hammerjs'

const container = ref(null)
let app = null
let sprite = null
let hammertime = null

onMounted(() => {
  // 创建 Pixi 应用
  app = new PIXI.Application({
    width: window.innerWidth,
    height: window.innerHeight,
    backgroundColor: 0x1e1e1e,
    resolution: window.devicePixelRatio || 1,
    autoDensity: true,
  })
  container.value.appendChild(app.view)

  // 加载图像
  sprite = PIXI.Sprite.from('https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg')
  sprite.anchor.set(0.5)
  sprite.x = app.screen.width / 2
  sprite.y = app.screen.height / 2
  sprite.interactive = true
  app.stage.addChild(sprite)

  // 绑定 Hammer.js 实现手势
  hammertime = new Hammer(app.view)
  hammertime.get('pinch').set({ enable: true })

  let currentScale = 1
  hammertime.on('pinchmove', (e) => {
    const scale = Math.max(0.5, Math.min(3, currentScale * e.scale))
    sprite.scale.set(scale)
  })
  hammertime.on('pinchend', (e) => {
    currentScale = sprite.scale.x
  })

  // 拖拽
  let dragging = false
  let lastPos = { x: 0, y: 0 }
  app.view.addEventListener('touchstart', (e) => {
    if (e.touches.length === 1) {
      dragging = true
      lastPos = { x: e.touches[0].clientX, y: e.touches[0].clientY }
    }
  })
  app.view.addEventListener('touchmove', (e) => {
    if (dragging && e.touches.length === 1) {
      const dx = e.touches[0].clientX - lastPos.x
      const dy = e.touches[0].clientY - lastPos.y
      sprite.x += dx
      sprite.y += dy
      lastPos = { x: e.touches[0].clientX, y: e.touches[0].clientY }
    }
  })
  app.view.addEventListener('touchend', () => {
    dragging = false
  })
})

onBeforeUnmount(() => {
  hammertime?.destroy()
  app?.destroy(true, { children: true })
})
</script>

<style scoped>
.canvas-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  touch-action: none; /* 防止默认滚动 */
}
</style>
